package io.netty.groupchat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * Netty 实现群聊服务端
 *
 * @author Verlet
 * @date 2023-02-04 21:33
 */
@Slf4j
public class GroupChatServer {

    private int port;

    public static int DEFAULT_PORT = 6784;

    public GroupChatServer() {
        this.port = DEFAULT_PORT;
    }

    public GroupChatServer(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    // 设置字符串形式的解码
                                    .addLast(new StringDecoder())
                                    // 设置字符串形式的编码
                                    .addLast(new StringEncoder())
                                    .addLast(new GroupChatServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    // 保持连接
                    .childOption(ChannelOption.SO_KEEPALIVE, true);


            ChannelFuture channelFuture = serverBootstrap.bind(port).sync()
                    .addListener((ChannelFutureListener) future -> {
                        if (future.isSuccess()) {
                            log.info("端口 [{}] 绑定成功", port);
                        } else {
                            log.error("端口 [{}] 绑定失败", port);
                        }
                    });
            log.info("服务端启动成功。。。");
            channelFuture.channel().closeFuture().sync();
        } finally {
            workGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        new GroupChatServer().run();
    }


}
